//Written by James McLaughlin
//Copyright (c) 2014 WAHS news
//before document load...
//hide the entire page to eliminate the unstyled flash of content

//determine vendor prefix
window.prefix = (function () {
  var styles = window.getComputedStyle(document.documentElement, ''),
    pre = (Array.prototype.slice
      .call(styles)
      .join('') 
      .match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
    )[1],
    dom = ('WebKit|Moz|MS|O').match(new RegExp('(' + pre + ')', 'i'))[1];
  return {
    dom: dom,
    lowercase: pre,
    css: '-' + pre + '-',
    js: pre[0].toUpperCase() + pre.substr(1)
  };
})();

//milliseconds to minutes/seconds
var milliToMinute = function (milli) {
	var seconds = milli/1000;
	var minutes = Math.floor(seconds/60);
	seconds = seconds%60;
	return (minutes > 0 ? (minutes === 1 ? minutes + ' minute' : minutes + ' minutes') : '') + ' ' + (seconds > 0 ? (seconds === 1 ? seconds.toFixed(2)+ ' second' : seconds.toFixed(2) + ' seconds') : '');
}

//video functions
var first = true;
function delvePlayerCallback(playerId, eventName, data) {

	var id = "delve_player_used";
	if (eventName == 'onPlayerLoad' && (DelvePlayer.getPlayers() == null || DelvePlayer.getPlayers().length == 0)) {
		DelvePlayer.registerPlayer(id);
	}

	switch (eventName) {
		case 'onPlayerLoad':
			doOnPlayerLoad();
			break;
		case 'onPlayStateChanged':
			if (data.isPlaying === true && delve_currentMediaStartPosition > 0) {
				DelvePlayer.doSeekToSecond(delve_currentMediaStartPosition / 1000);
				delve_mediaStartPosition = 0;
			}
			// track pause and play
			if (data.isPlaying != previous_is_playing) {
				var video = DelvePlayer.doGetCurrentMedia()
				var offset = DelvePlayer.doGetPlayheadPositionInMilliseconds()/1000
				var title = data.isLive != '' && data.isLive != undefined ? video.title + ' LIVE' : video.title;
				if (data.isPlaying) { // on play
					if (first) {
						setTimeout(function () {DelvePlayer.doPause();}, 200);
						console.log("Paused");
						first = false;
					}
					log('play state changed: play:' + title + ', offset:' + offset)
					s.Media.play(title, offset)
				}
				else { // on pause
					log('play state changed: pause:' + title + ', offset:' + offset)
					s.Media.stop(title, offset)
				}
			}
			previous_is_playing = data.isPlaying
			break;
		case 'onMediaComplete':
			doOnMediaComplete(data);
			break;
		case 'onError':
			//because we don't use the order in the channel we may reach the "last" video and the channel may be complete before our thumbnail bar has played out
			log(data.errorID);
			break;
		case 'onMediaLoad':
			if ((data.isLive != '') && (isOSplayer == false)) {
				jQuery('#videoPlayerType').html('Live');
			}

			//print title in title area and live or ondemand in header
			//find title from html in carousel
			var title = ''

			if (window.location.href.indexOf('videos.aspx') === -1) {
				jQuery('#carouselPanel .carousel-thumbs li .llid').each(function (llMediaID) {
					var llMediaID = data.id;
					var thisllMediaID = jQuery(this)[0].innerHTML;
					if (thisllMediaID == llMediaID) {
						title = jQuery(this)[0].parentElement.children[1].innerHTML;
						jQuery('#currentVideoTitle').html(title + ' (' + milliToMinute(DelvePlayer.doGetCurrentMedia().durationInMilliseconds) + ')');
					}
				});
			}
			else {
				title = jQuery('#'+delve_currentMediaID+' b').html()
			}

			if (data.isLive != '')
				title += ' LIVE'

			// analytics
			var video = DelvePlayer.doGetCurrentMedia()
			var duration = video.durationInMilliseconds/1000
			s.Media.open(title, duration, 'School Player')
			s.Media.play(title, 0)
			log('media load: open and play:' + title + ', ' + duration + 'sec')

			setCopyLink(delve_currentMediaID, 0)

			break;
	}
}

//bind hover listeners to animate menu
$('ul.menu').children('li').hover(function() {
	$(this).css({"background":""+window.prefix['css']+"linear-gradient(rgb(249, 244, 100), rgb(255, 251, 103))"});
	$('ul', this).stop(true, true).slideDown(400);
}, function() {
	$(this).css({"background":""+window.prefix['css']+"linear-gradient(rgb(220, 220, 220), rgb(200, 200, 200))"});
	$('ul', this).stop().slideUp(250);
});

$('ul.menu').children('li').children('ul').children('li').children('a').click(function (event) {
	var toLoad = $(this).attr('href');
	//var loader = $('<img></img>').attr('src', 'https://useducationtvahs.googlecode.com/svn/trunk/ajaxload.gif').attr('id', 'progBar');
	//console.log(loader);
	//loader.insertAfter($('ul.menu').children('li').eq(3));
	$('#animatedContent').fadeOut(750, loadContent);
	
	function loadContent() {
		$.ajax({
			type: "GET",
			url: toLoad,
			dataType: "html", 
			success: function(html){
				//until the video glitch is fixed, do not animate if target page has videos
				var objTest = $('<div></div>').html(html);
				if ($(objTest).find('div#video_player_content').length > 0 || $(objTest).find('form#aspnetForm').length > 0) {
					reloadPage();
				} else {
					var animated = extractAnimation(html);
					$('#animatedContent').html(animated);
					if ($('body').hasClass('index')) {
						$('body').removeClass('index').addClass('subpage');
					}
					$('div#animatedContent').find('script').each(function(i) {
						eval($(this).text());
					});
					showNewContent();
					//$('img#progBar').remove();
					//delete loader;
				}
			},
			error: function () {
			}
		});	
	}
	function extractAnimation (input) {
		var obj = $('<div></div>').html(input);
		obj.find('script').each(function(i) {
			if ($(this).attr('id')=='PrepareFunctions' || $(this).attr('id')=='IncludeToModify') {
				eval($(this).text());
			}
		});
		var container = $(obj).find('div#container').children();
		container = container.not('div#header');
		container = container.not('div#topstripe');
		var modContainer = $('<div></div>');
		container.each(function(index, element) {
            modContainer.append(element);
        });
		var answer = modContainer.html();
		return answer;
	}
	function showNewContent () {  
		$('#animatedContent').fadeIn(750); 
	}
	function reloadPage () {
		window.location = toLoad;
	}
	return false;
});

//on document load...
$(document).ready(function() {
	//selectively modify DOM to make page animations easier
	if (!($("div#animatedContent").length > 0)) {
		//alert('entered');
		var header = $('div#header').detach();
		$('div#container').prepend(header);
		var newDiv = $('<div></div>').attr('id', 'animatedContent');
		var endPoint = $('div#content');
		$('div.videostripe').nextUntil(endPoint).addBack().add(endPoint).wrapAll(newDiv);
		//remove menu links on top part
		$("ul.menu").children('li').not(':first').children('a').removeAttr('href');
		$("ul.menu").children('li:first').children('a').attr('href', 'http://www.useducationtv.com/default.aspx?sid=61172');
		//remove the ad on the bottom of the school logo/animation thingy
		$('div.banner').prepend($('<div></div>').attr('id', 'bannerholder').css({"width":"607px", "height":"75px", "overflow":"hidden"}).add($('<div></div>').attr('id', 'bannerparts')));
		$('div.banner').children('iframe').appendTo('div#bannerholder');
		//slide bottom two elements up to account for the increase in vertical space
		$('div.above-banner-stripe').css({"top":"80px"});
		$('div.banner-stripe').css({"top":"90px"});
		//adjust bottom video share button
		//force banner 'cause this template is temperamental
		$('div#bannerholder').html('<img src="http://www.useducationtv.com/upload/6559/content/temp_banner.jpg"></img>');
		//$('div#bannerholder').html('<iframe src="http://files.bannersnack.com/iframe/embed.html?hash=bu3a759m&bgcolor=%233D3D3D&wmode=opaque&t=1395340171" width="607" height="90" seamless="seamless" scrolling="no" frameborder="0" allowtransparency="true"></iframe>');
		$('div#video_player_content div.share').css({'position':'relative', 'top':'-10px'});
		
		//heavily modify menu bar area
		$('div.header').css({"background":"none", "background":""+window.prefix['css']+"linear-gradient(rgb(255, 255, 255), rgb(230, 230, 230))", "height":"201px"});
		$('ul.menu').children('li.search').prev().remove(); 
		$('ul.menu').children('li').not(':last').css({"background":"none", "border":"2px inset black", "background":""+window.prefix['css']+"linear-gradient(rgb(220, 220, 220), rgb(200, 200, 200))", "height":"42px", "border-radius":"15px", "margin":"3px 5px 0px 0px", "line-height":"42px", "-webkit-user-select":"none", "-moz-user-select":"none", "-ms-user-select":"none", "-o-user-select":"none", "user-select":"none"}).addClass('real');
		$('ul.menu').css({"background":"none"});
		$('ul.menu').children('li').children('a').css({"padding-top":"13px"});
		$('ul.menu').children('li').first().css({"margin":"3px 5px 0px 5px"});
		$('div#menu').css({"top":"2px", "height":"54px", "border-top":"2px solid black"});
		//inject CSS to override external CSS which seriously messes up menu functions
		$("<style type='text/css'>.menu li:hover ul, #menu li.hover ul,.menu ul li:hover ul, #menu ul li.hover ul,.menu ul ul li:hover ul, #menu ul ul li.hover ul { 	display: none;	left:0;}.menu li ul,.menu ul li ul,.menu ul ul li ul {left:0px}</style>").appendTo('head');
		$('ul.menu').children('li').children('ul').hide().css({"margin-top":"2px", "border-radius":"10px", "overflow":"hidden"});	
		//remove top ad and replace it with text
		//$('div#header').children('div.bannerad').children('iframe').remove();
		$('div#header').prepend($('<h1></h1>').text("WAHS").css({"color":"black)", "font-size":"7em", "font-family":"sans-serif", "text-align":"center", "text-shadow":"-2px -2px 0 rgb(255, 215, 0), 2px -2px 0 rgb(255, 215, 0), -2px 2px 0 rgb(255, 215, 0), 2px 2px 0 rgb(255, 215, 0)"}));
		$('div#header').css({"margin-top":"10px"});
		//$('div.strip').css({"background-color":"#FFDF00"});
		
		//weird header bug
		console.log($('div[id^="Header1"]').remove());
	}
});
